package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;



@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper mapper;
    @Override
    public R login(Employee employee) {
        if (employee==null){
            return R.error("参数非法");
        }
        String password = employee.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee employee1 = mapper.selectOne(wrapper);
        if (employee1==null){
            return R.error("用户名不存在");
        }
        if (!employee1.getPassword().equals(passwordMd5)){
            return R.error("密码错误");
        }
        if (employee1.getStatus()==0){
            return R.error("该用户已禁用");
        }
        return R.success(employee1);
    }

    @Override
    public R save(Employee employee) {
        int i = mapper.insert(employee);
        if (i==1){
            return R.success("添加成功");
        }else {
            return R.success("添加失败");

        }
    }

    @Override
    public R page(int page, int pageSize, String name) {
        IPage<Employee> p = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);
        IPage<Employee> page1 = mapper.selectPage(p, wrapper);
        return R.success(page1);
    }

    @Override
    public R update(Employee employee) {
        Employee employee1 = mapper.selectById(employee.getId());
        if (employee1!=null){
//            employee1.setStatus(employee.getStatus());
//            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(Employee::getId,employee.getId());
            mapper.updateById(employee);
            return R.success("修改成功");
        }
        return R.error("修改成功");
    }

    @Override
    public R findById(Long id) {
        Employee employee = mapper.selectById(id);
        return R.success(employee);
    }
}
